package give.my.money.back;

import java.io.InputStream;

import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.ContactsContract;
import android.util.Log;
import android.widget.ImageView;
import android.widget.SimpleCursorAdapter;



public class MySimpleCursorAdapter extends SimpleCursorAdapter {

	private static ContentResolver cr;
	
    public MySimpleCursorAdapter(Context context, int layout, Cursor cur,
             String[] from, int[] to) {
        super(context, layout, cur, from, to);
       	cr = context.getContentResolver();
    }

    @Override 
    public void setViewImage(ImageView iv, String text)
    {
    	Bitmap contactPic;
    	Log.d("BMMB", "Text _ID" + text);
        Cursor cursor = cr.query(ContactsContract.Data.CONTENT_URI, null,
            "_id = '" + text + "'", null, null);
       cursor.moveToFirst();
       String id = cursor.getString(cursor.getColumnIndex(ContactsContract.Data.RAW_CONTACT_ID));
       Log.d("BMMB", "RawContactID" + id);
       contactPic = loadContactPhoto(cr,Integer.parseInt(id));
       if (contactPic != null){
    	   iv.setImageBitmap(contactPic);
       }
       else{//Set a default image if the contact has not one.
           iv.setImageResource(R.drawable.ic_launcher);
       }

    }
    
    public static Bitmap loadContactPhoto(ContentResolver cr, long  id) {
        Uri uri = ContentUris.withAppendedId(ContactsContract.Contacts.CONTENT_URI, id);
        String x = uri.toString();
        InputStream input;
        input = ContactsContract.Contacts.openContactPhotoInputStream(cr, uri);
        if (input == null){
        	return null;       
        }
        
        return BitmapFactory.decodeStream(input);
        }
    
 
}
